import { Form, Input, message, Modal, Radio } from "antd"
import { useImperativeHandle, useState } from "react"
import { useRequest } from "umi"

interface PropsType {
  cRef: any,
  submit: () => void,
}
interface dataType {
  username: string,
  password: string,
  roleId: number,
}

const EditForm: React.FC<PropsType> = ({ cRef, submit }) => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [typeModal, setTypeModal] = useState(1)
  const [form] = Form.useForm()

  useImperativeHandle(cRef, () => ({
    open: (type: number, data?: dataType) => {
      if (data) {
        form.setFieldsValue(data)
      }
      setTypeModal(type)
      setIsModalVisible(true)
    }
  }))

  const { run: addApi, loading: addLoading } = useRequest((data) => ({
    url: '',
    method: 'post',
    data
  }), { manual: true })

  const { run: updateApi, loading: updateLoading } = useRequest((data) => ({
    url: '/api/user/updateUser',
    method: 'post',
    data
  }), { manual: true })

  const handleOk = () => {
    form.validateFields().then(async values => {
      if (typeModal === 1) {
        await addApi(values)
      } else {
        await updateApi(values)
      }
      submit()
      message.success('操作成功')
      setIsModalVisible(false);
      form.resetFields();
    }).catch(() => { })
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };
  return <Modal
    title={typeModal === 1 ? "新增" : "修改"}
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    confirmLoading={addLoading || updateLoading}
  >
    <Form
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, message: '请输入用户名!' }]}
      >
        <Input disabled size='large' />
      </Form.Item>
      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password size='large' />
      </Form.Item>
      <Form.Item label="角色" name="roleId" rules={[{ required: true, message: '请选择用户权限' }]}>
        <Radio.Group>
          <Radio value={3}>学生</Radio>
          <Radio value={2}>教师</Radio>
          <Radio value={1}>管理员</Radio>
        </Radio.Group>
      </Form.Item>
    </Form>
  </Modal>
}

export default EditForm